<template>
	<view class="process-container">
		<u-navbar title="处理隐患" :is-back="true" back-icon-color="#ffffff" title-color="#ffffff" :background="{ background: '#1a4380' }"></u-navbar>
		<view class="content">
			<view class="info-card">
				<view class="info-item">
					<text class="label">隐患描述：</text>
					<text class="value">{{dangerInfo.hazardDesc || '暂无'}}</text>
				</view>
				<view class="info-item" v-if="dangerInfo.level">
					<text class="label">隐患等级：</text>
					<text class="value">{{dangerInfo.level}}</text>
				</view>
				<view class="info-item">
					<text class="label">发现时间：</text>
					<text class="value">{{formatDateTime(dangerInfo.discoveryTime) || '暂无'}}</text>
				</view>
				<view class="info-item">
					<text class="label">隐患位置：</text>
					<text class="value">{{dangerInfo.hazardLocation || '暂无'}}</text>
				</view>
				<view class="info-item" v-if="dangerInfo.imagePaths && dangerInfo.imagePaths.length">
					<text class="label">隐患图片：</text>
					<view class="image-list">
						<image v-for="(img, index) in dangerInfo.imagePaths" :key="index" :src="img" mode="aspectFill" @click="previewImage(img, dangerInfo.imagePaths)"></image>
					</view>
				</view>
			</view>
			
			<view class="process-form">
				<view class="form-title">处理信息</view>
				<view class="form-item">
					<text class="form-label">处理结果</text>
					<textarea class="form-input" v-model="processResult" placeholder="请输入处理结果"></textarea>
				</view>
				<view class="form-item">
					<text class="form-label">上传处理后图片</text>
					<view class="upload-box">
						<view class="upload-item" v-for="(item, index) in processImages" :key="index">
							<image :src="item" mode="aspectFill" @click="previewImage(item, processImages)"></image>
							<view class="delete-icon" @click="deleteImage(index)">×</view>
						</view>
						<view class="upload-btn" @click="chooseImage" v-if="processImages.length < 4">
							<text class="iconfont icon-camera">+</text>
							<text class="upload-text">上传</text>
						</view>
					</view>
				</view>
				<view class="form-btns">
					<button class="submit-btn" @click="submitProcess">提交处理结果</button>
				</view>
			</view>
		</view>
		
		<u-toast ref="uToast"></u-toast>
		<u-popup :show="showLoading" mode="center" :closeable="false">
			<view class="loading-popup">
				<u-loading :show="true" mode="circle" color="#1a4380"></u-loading>
				<text class="loading-text">处理中...</text>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			id: '',
			dangerInfo: {},
			processResult: '',
			processImages: [],
			showLoading: false,
			uploadedImageList: [], // MinIO上传后的图片URL
			uploading: false // 上传状态标志
		}
	},
	onLoad(options) {
		if (options.id) {
			this.id = options.id
			this.getDangerDetail()
		}
	},
	methods: {
		// 获取隐患详情
		getDangerDetail() {
			uni.showLoading({
				title: '加载中'
			})
			
			uni.request({
				url: 'http://172.20.10.3:9527/security/hazard/getOneById',
				method: 'GET',
				data: {
					id: this.id
				},
				success: (res) => {
					console.log('详情数据:', res.data)
					if (res.statusCode === 200 && res.data.code === 200) {
						this.dangerInfo = res.data.data
						
						// 检查状态是否为待处理
						if (this.dangerInfo.status !== 1) {
							uni.showToast({
								title: '该隐患不是待处理状态',
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						}
					} else {
						this.$refs.uToast.show({
							type: 'error',
							message: res.data.message || '获取隐患详情失败'
						})
					}
				},
				fail: (err) => {
					console.error('请求失败:', err)
					this.$refs.uToast.show({
						type: 'error',
						message: '网络异常，请稍后重试'
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		},
		// 格式化日期时间
		formatDateTime(dateString) {
			if (!dateString) return ''
			const date = new Date(dateString)
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			const hour = date.getHours().toString().padStart(2, '0')
			const minute = date.getMinutes().toString().padStart(2, '0')
			
			return `${year}-${month}-${day} ${hour}:${minute}`
		},
		// 选择图片
		chooseImage() {
			uni.chooseImage({
				count: 4 - this.processImages.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.processImages = [...this.processImages, ...res.tempFilePaths]
				}
			})
		},
		// 删除图片
		deleteImage(index) {
			this.processImages.splice(index, 1)
		},
		// 预览图片
		previewImage(current, urls) {
			uni.previewImage({
				urls: urls,
				current: current
			})
		},
		// 提交处理结果
		submitProcess() {
			// 表单验证
			if (!this.processResult.trim()) {
				this.$refs.uToast.show({
					type: 'error',
					message: '请输入处理结果'
				})
				return
			}
			
			if (this.processImages.length === 0) {
				this.$refs.uToast.show({
					type: 'error',
					message: '请上传处理后的图片'
				})
				return
			}
			
			// 检查是否有图片正在上传
			if (this.uploading) {
				this.$refs.uToast.show({
					type: 'error',
					message: '图片正在上传中，请稍候'
				})
				return
			}
			
			// 显示加载状态
			this.showLoading = true
			
			// 开始上传所有图片
			const uploadPromises = this.processImages.map(image => this.uploadImageToMinio(image))
			
			// 等待所有图片上传完成
			Promise.all(uploadPromises)
				.then(() => {
					// 提交处理结果
					return this.submitProcessResult()
				})
				.then(() => {
					this.showLoading = false
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					
					// 返回列表页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				})
				.catch(error => {
					this.showLoading = false
					this.$refs.uToast.show({
						type: 'error',
						message: error
					})
				})
		},
		// 上传图片到MinIO
		uploadImageToMinio(imagePath) {
			return new Promise((resolve, reject) => {
				// 构建文件名：使用时间戳+随机数确保唯一性
				const timestamp = new Date().getTime()
				const random = Math.floor(Math.random() * 1000)
				const extension = imagePath.substring(imagePath.lastIndexOf('.'))
				const fileName = `hazard_process_${timestamp}_${random}${extension}`
				
				this.uploading = true
				
				uni.uploadFile({
					url: 'http://172.20.10.3:9527/security/file/upload',
					filePath: imagePath,
					name: 'file',
					formData: {
						'fileName': fileName,
						'bucket': 'zhxy' // MinIO存储桶名称
					},
					success: (uploadRes) => {
						try {
							// 解析响应结果
							const result = JSON.parse(uploadRes.data)
							
							if (result.code === 200) {
								// 上传成功，保存MinIO返回的URL
								const imageUrl = result.data
								this.uploadedImageList.push(imageUrl)
								
								console.log('图片上传成功:', imageUrl)
								resolve(imageUrl)
							} else {
								console.error('图片上传失败:', result)
								reject(result.message || '图片上传失败')
							}
						} catch (e) {
							console.error('解析上传结果失败:', e)
							reject('解析上传结果失败')
						}
					},
					fail: (err) => {
						console.error('图片上传请求失败:', err)
						reject('网络请求失败')
					},
					complete: () => {
						this.uploading = false
					}
				})
			})
		},
		// 提交处理结果
		submitProcessResult() {
			return new Promise((resolve, reject) => {
				// 使用上传后的MinIO图片URL
				const processImages = this.uploadedImageList
				
				// 构建符合 SafetyHazard 类的请求对象
				const safetyHazard = {
					id: this.id,
					tishi: this.processResult, // 将处理结果作为 tishi 字段传给后端
					status: 2, // 更新为待验证状态
					// handler: uni.getStorageSync('userInfo')?.username || '当前用户'
				}
				
				// 基础URL
				let url = 'http://172.20.10.3:9527/security/hazard/process'
				
				// 添加processImages作为请求参数
				let urlWithParams = url
				if (processImages && processImages.length > 0) {
					processImages.forEach((img, index) => {
						urlWithParams += (index === 0 ? '?' : '&') + `processImages=${encodeURIComponent(img)}`
					})
				}
				
				console.log('提交处理结果, URL:', urlWithParams)
				console.log('提交处理结果, 数据:', safetyHazard)
				console.log('提交处理结果, 图片:', processImages)
				
				uni.request({
					url: urlWithParams,
					method: 'POST',
					data: safetyHazard, // 直接传递符合SafetyHazard类的对象
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						console.log('处理结果提交响应:', res.data)
						if (res.statusCode === 200 && res.data.code === 200) {
							resolve()
						} else {
							reject(res.data.message || '提交处理结果失败')
						}
					},
					fail: (err) => {
						console.error('处理结果提交请求失败:', err)
						reject('网络请求失败')
					}
				})
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.process-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	
	.content {
		padding: 20rpx;
	}
	
	.info-card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 20rpx;
		
		.info-item {
			margin-bottom: 24rpx;
			
			.label {
				color: #666;
				font-size: 28rpx;
				margin-right: 10rpx;
			}
			
			.value {
				color: #333;
				font-size: 28rpx;
				word-break: break-all;
			}
			
			.image-list {
				display: flex;
				flex-wrap: wrap;
				margin-top: 10rpx;
				
				image {
					width: 160rpx;
					height: 160rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					border-radius: 8rpx;
				}
			}
		}
	}
	
	.process-form {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.form-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 30rpx;
		}
		
		.form-item {
			margin-bottom: 30rpx;
			
			.form-label {
				display: block;
				font-size: 28rpx;
				color: #333;
				margin-bottom: 15rpx;
			}
			
			.form-input {
				width: 100%;
				height: 200rpx;
				background-color: #f8f8f8;
				border-radius: 8rpx;
				padding: 20rpx;
				font-size: 28rpx;
				box-sizing: border-box;
			}
			
			.upload-box {
				display: flex;
				flex-wrap: wrap;
				
				.upload-item, .upload-btn {
					width: 160rpx;
					height: 160rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					border-radius: 8rpx;
					overflow: hidden;
					position: relative;
				}
				
				.upload-item {
					image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
					
					.delete-icon {
						position: absolute;
						top: 0;
						right: 0;
						width: 40rpx;
						height: 40rpx;
						background-color: rgba(0, 0, 0, 0.5);
						color: #fff;
						font-size: 30rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
				
				.upload-btn {
					background-color: #f8f8f8;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					.iconfont {
						font-size: 50rpx;
						color: #999;
					}
					
					.upload-text {
						font-size: 24rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}
			}
		}
		
		.form-btns {
			margin-top: 40rpx;
			
			.submit-btn {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				background-color: #1a4380;
				color: #fff;
				font-size: 32rpx;
				border-radius: 44rpx;
			}
		}
	}
	
	.loading-popup {
		width: 240rpx;
		height: 240rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.loading-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #666;
		}
	}
}
</style> 